# encoding:utf-8

import tkinter.messagebox
from tkinter import *
import imgsb
import bdimg
import BaiduTrans
import os
import ico
import base64

# 主程序类
class identification():

    win = Tk()
    win_one = Frame(win, relief=RAISED, bg="red")
    win_sl = Frame(win, relief=RAISED, bg="blue")

    text_ed = Text(win_one, width=50, height=20, undo=True, maxundo=5)
    text_rd = Text(win_one, width=50, height=20, undo=True, maxundo=5)

    def __init__(self):
        self.init()

    def init(self):
        with open('tmp.ico', 'wb') as tmp:
            tmp.write(base64.b64decode(ico.Ico().img))
        self.win.iconbitmap('tmp.ico')
        os.remove('tmp.ico')

        self.win.title(string="识别文字并翻译")

        self.win_one.pack(side=TOP, fill=BOTH, expand=1)
        self.win_sl.pack(side=TOP, fill=BOTH, expand=0)

        self.text_ed.pack(side=LEFT, fill=BOTH, expand=1)
        self.text_rd.pack(side=LEFT, fill=BOTH, expand=1)

        Button(self.win_sl, text="识别文字", command=self.shibie).pack(side=LEFT, fill=X, expand=1)
        Button(self.win_sl, text="文字翻译", command=self.fanyi).pack(side=LEFT, fill=X, expand=1)

        self.text_du(self.text_ed)
        self.text_fan(self.text_rd)

        self.win.mainloop()

    def text_du(self, jubin, data=[{'words': '请先使用其他截图软件进行截图后，按键识别内容！'}]):
        if data[0] != {'words': '请先使用其他截图软件进行截图后，按键识别内容!'}:
            self.text_ed.delete('0.0', END)
        for i in data:
            jubin.insert(INSERT, i['words']+'\n')

    def text_fan(self,jubin,data=[{'dst': '翻译框内必须要内容才能进行翻译！'}]):
        if data[0] != {'words': '请先使用其他截图软件进行截图后，按键识别内容!'}:
            self.text_rd.delete('0.0', END)
        for i in data:
            jubin.insert(INSERT, i['dst']+'\n')

    def shibie(self):
        img = imgsb.imgsb()
        imgres = img.saveimg()
        if imgres['state'] == 0:
            tkinter.messagebox.showerror("错误", imgres['message'])
        else:
            orj = bdimg.bdimg()
            self.text_du(self.text_ed, orj.ty_text())
            os.remove('1.png')

    def fanyi(self):
        text = self.text_ed.get('0.0', END)

        res = BaiduTrans.fanyi()
        data = res.gettext(text)
        # {'from': 'en', 'to': 'zh', 'trans_result': [{'src': 'apple', 'dst': '苹果'}]}
        if data['trans_result']:
            self.text_fan(self.text_rd,data['trans_result'])
        else:
            tkinter.messagebox.showerror("错误", '无法翻译左框内容')

if __name__ == '__main__':
    identification()

